package com.ss.service.impl;

import com.ss.dto.LoginUserDto;
import com.ss.entity.User;
import com.ss.redis.RedisCache;
import com.ss.response.ResponseResult;
import com.ss.service.UserLoginService;
import com.ss.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class UserLoginServiceImpl implements UserLoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        //获取 AuthenticationManager 对象
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authentication);
        if(Objects.isNull(authenticate)){
            log.info("login fail");
            throw new RuntimeException("登录失败");
        }
        LoginUserDto principal = (LoginUserDto)authenticate.getPrincipal();
        String userId = principal.getUser().getId().toString();
        String jwt = JwtUtils.createJWT(userId);
        Map<String, String> result = new HashMap<>();
        result.put("token", jwt);

        principal.setJwtToken(jwt);
        redisCache.setCacheObject("login:" + userId, principal);

        return new ResponseResult(200, "success", result);
    }

    @Override
    public ResponseResult logout(){
        SecurityContext holder = SecurityContextHolder.getContext();
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken)holder.getAuthentication();
        if(usernamePasswordAuthenticationToken==null){
            log.info("logout fail-1");
            throw new RuntimeException("登出失败");
        }
        LoginUserDto loginUserDto = (LoginUserDto)usernamePasswordAuthenticationToken.getPrincipal();
        if(loginUserDto == null){
            log.info("logout fail-2");
            throw new RuntimeException("登出失败");
        }
        redisCache.deleteObject("login:" + loginUserDto.getUser().getId());
        return new ResponseResult(200, "success");

    }

}
